package core

import (
	"fmt"
	"go.uber.org/zap"
	initialize "melon/server"
	"melon/server/global"
	"os"
	"os/exec"
	"runtime"
	"time"
)

type server interface {
	ListenAndServe() error
}

func open(url string) error {
	var cmd string
	var args []string

	switch runtime.GOOS {
	case "windows":
		cmd = "cmd"
		args = []string{"/c", "start"}
	case "darwin":
		cmd = "open"
	default: // "linux", "freebsd", "openbsd", "netbsd"
		cmd = "xdg-open"
	}
	args = append(args, url)
	return exec.Command(cmd, args...).Start()
}

func RunWindowsServer() {
	Router := initialize.InitWebRouter()

	address := global.ConfigYml.GetString("HttpServer.Port")
	s := initServer(address, Router)

	time.Sleep(10 * time.Microsecond)
	global.ZapLog.Info("server run success on ", zap.String("address", address))

	_ = open("http://localhost:8088/")

	err := s.ListenAndServe()
	if err != nil {
		global.ZapLog.Info(err.Error())
	}
	global.ZapLog.Info(fmt.Sprintf("Server on %s stopped", address))
	os.Exit(0)
}
